package com.qfedu.filter;

import com.qfedu.entity.Result;
import com.qfedu.service.IUserService;
import com.qfedu.service.impl.UserService;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/login.jsp")
public class LoginFilter implements Filter {
    IUserService userService = new UserService();
    public void destroy() {
    }
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
       //String cookie = (String) request.getSession().getAttribute("loginCookie");
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("autoLogin")){
                String string = cookie.getValue();
                String username = string.substring(0,string.indexOf(":"));
                String password = string.substring(string.indexOf(":")+1);
                Result result = userService.checkUser(username, password, "1234", "1234");
                if (result.isSuccess()){
                    request.getSession().setAttribute("user",result.getDate());
                    response.sendRedirect("index.jsp");
                }
            }
        }
        chain.doFilter(request, response);
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
